<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="500px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号" prop="loginName">
              <el-input
                class="data-input"
                v-model="form.loginName"
                placeholder="请输入"
                :disabled="!!props.detail.pkid"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="真实姓名" prop="userName">
              <el-input
                class="data-input"
                v-model="form.userName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!props.detail.pkid">
            <el-form-item label="密码" prop="loginPassword">
              <el-input
                class="data-input"
                v-model="form.loginPassword"
                placeholder="请输入"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!props.detail.pkid">
            <el-form-item label="确认密码" prop="reLoginPassword">
              <el-input
                class="data-input"
                v-model="form.reLoginPassword"
                placeholder="请输入"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色" prop="roleId">
              <el-select
                class="search-select"
                v-model="form.roleId"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of roleOptions"
                  :key="index"
                  :label="item.roleName"
                  :value="item.pkid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                class="data-input"
                v-model="form.remark"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否启用">
              <el-radio-group v-model="form.userState">
                <el-radio
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :value="Number(item.value)"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cardId } from '@/utils/validate'
import { CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import { userAdd, getUserDetail } from '@/api/manager/systemManage/user.js'
import { getRoleList } from '@/api/manager/systemManage/role.js'
import { useDict } from '@/hooks/useDict'
const { dict } = useDict(['yn'])
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  async () => {
    if (props.detail.pkid && dialogVisible.value) {
      handleDetail()
    } else {
      form.value.type = props.detail.type
    }
  },
)
const handleDetail = async () => {
  const res = await getUserDetail({ pkid: props.detail.pkid })
  if (res.success) {
    form.value = { ...res.data.userInfo }
  } else {
    ElMessage.error(res.message)
  }
}
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = { userState: 1, isPatrol: 0 }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const defaultProps = {
  children: 'children',
  label: 'name',
}
const formRef = ref(null)
const form = ref({ userState: 1, isPatrol: 0 })

const rules = ref({
  loginName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  loginPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$/,
      message: '至少包含大写字母、小写字母、数字和特殊符号中其中三种',
      trigger: 'blur',
    },
  ],
  reLoginPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$/,
      message: '至少包含大写字母、小写字母、数字和特殊符号中其中三种',
      trigger: 'blur',
    },
  ],
})

const roleOptions = ref([])
const initRoleOptions = async () => {
  const res = await getRoleList({ pageIndex: 1, pageSize: 9999 })
  roleOptions.value = res.data.list
}

const loading = ref(false)
const handleSubmit = async () => {
  console.log(form.value)
  if (form.value.loginPassword !== form.value.reLoginPassword) {
    ElMessage.warning('确认密码与密码不同，请重新输入')
    return
  }
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      if (!params.pkid) {
        params.loginPassword = window.btoa(form.value.loginPassword)
      }
      delete params.reLoginPassword

      try {
        let res = await userAdd({ userInfoAo: params })
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}

watch(
  () => dialogVisible.value,
  () => {
    if (dialogVisible.value) {
      initRoleOptions()
    }
  },
)
defineExpose({ dialogVisible, title })
onMounted(() => {})
</script>
<style lang="scss" scoped></style>
